package cn.anquing.demo.mybatisplus.config;

//import cn.hutool.core.thread.ThreadFactoryBuilder;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.context.support.AbstractApplicationContext;

import java.util.concurrent.*;


/**
 * 事件监听器异步执行配置
 * @author wangqq65
 * @since 2021/9/16 15:17
 */
@Configuration
public class EventExecutorConfig {

    @Bean("eventExecutor")
    public Executor initExecutor() {

        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("eventExecutor-").build();
        Executor taskExecutor = new ThreadPoolExecutor(5, 10,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
        return taskExecutor;
    }

    @Bean(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME)
    public ApplicationEventMulticaster initEventMulticaster(@Qualifier("eventExecutor") Executor taskExecutor) {

        SimpleApplicationEventMulticaster simpleApplicationEventMulticaster = new SimpleApplicationEventMulticaster();

        simpleApplicationEventMulticaster.setTaskExecutor(taskExecutor);

        return simpleApplicationEventMulticaster;
    }

}
